import {
	ref
} from "vue";

import {
	getLatestVersion
} from "@/api/systemInfo/index.js";

function throttle(fn, delay) {
	let canRun = true;
	console.log('hhhhhhhhh')
	return function() {
		if (!canRun) return;
		canRun = false;
		setTimeout(() => {
			fn.apply(this, arguments);
			canRun = true;
		}, delay);
	};
}

let intervalId = null; //迭代器
class Upgrade {
	constructor() {
		this.isTest = false
		this.downloadUrl = "https:XXXXX.apk";
		this.progress = ref(0);
		this.packName = "com.sczx.reservation"
		this.testPackName = "com.sczx.reservation"
		this.signature = "shuchuangzhixin";
		this.versionCode = 1000;
		this.latestVersion = 1000;
		this.throttledDebounce = throttle(this.debounce.bind(this), 250);

	}
	setLastVersion = (latestVersion) => {
		this.latestVersion = latestVersion
	}
	getLocalVersion = () => { //获取本地版本
		return new Promise((resolve, reject) => {
			const version = plus.runtime.versionCode
			this.versionCode = version
			resolve(version);
		}).catch((err) => {
			console.error(err);
		});
	};

	getLatestVersion = (localVersion) => { //获取线上版本
		console.log('当前本地版本3', localVersion)
		return new Promise((resolve, reject) => {
			let item = {
				packName: this.testPackName,
				signature: this.signature,
				versionCode: localVersion
			};
			console.log('本地版本上传item', item)
			getLatestVersion(item).then((res) => {
				console.log('res', res)
				if (res.data.success) {
					if (res.data.data != null) {
						resolve(res.data.data);
					} else {
						resolve('当前已是最新版本');
					}
				} else {
					reject('获取最新版本失败');
				}
			}).catch((error) => {
				reject(error);
			});
		});
	};
	checkVersion = async (time = 1000 * 30) => {
		console.log('当前线上版本1')

		let latestObj
		if (intervalId == null) {
			intervalId = setInterval(async () => {

				const localVersion = await this.getLocalVersion();
				latestObj = await this.getLatestVersion(localVersion);
				this.latestVersion = latestObj.versionCode
				console.log('最新版本', this.latestVersion)

				if (localVersion === latestObj.versionCode || this.latestVersion ==
					undefined) {} else {
					clearInterval(intervalId); // 清除之前的定时任务
					intervalId = null;
					this.updatePackage(latestObj.url)
				}
			}, time)
		}
	};

	checkVersionOnlyOne = async () => {
		let latestObj
		const localVersion = await this.getLocalVersion();
		console.log('当前bd版本3', localVersion)
		latestObj = await this.getLatestVersion(localVersion);
		console.log('当前线上版本2', latestObj)
		// this.latestVersion = latestObj.versionCode
		return {
			localVersion,
			latestObj: latestObj
		};

	};
	updatePackage = (url = "") => {
		console.log('最新版本链接', url)
		uni.showModal({
			title: "检测到有版本更新！",
			content: `当前版本${this.versionCode},最新版本${this.latestVersion}请升级app到最新版本！`,
			cancelText: "取消",
			confirmText: "立即升级",
			success: (res) => {
				this.downloadUrl = url
				if (res.confirm) {
					this.downloadPackage();
				} else {
					setTimeout(() => {
						this.checkVersion()
					}, 24 * 60 * 60 * 1000)
				}
			},
		});
	};

	downloadPackage = () => {
		const task = plus.downloader.createDownload(
			this.downloadUrl, {},
			(res, status) => {
				console.log('下载状态', status)
				if (status === 200) {
					plus.runtime.install(res.filename);

				} else {
					console.log('下载失败')
					uni.hideToast()
					uni.showToast({
						title: '自动更新失败',
						icon: 'error'
					})
					uni.showModal({
						title: '自动更新失败，是否下载完整包',
						success() {

						}
					})
				}
			}
		);

		this.onProgress(task);
		task.start();
	};

	onProgress = (task) => {
		// console.log('开始加载进度条')
		uni.showLoading({
			title: '下载中...',
			mask: true,
		});

		task.addEventListener(
			"statechanged",
			(e) => {
				console.log('开始加载进度条', e.state)
				if (e && e.downloadedSize > 0) {
					const progress = (
						(e.downloadedSize / e.totalSize) *
						100
					).toFixed(2);
					this.progress.value = progress;

					this.throttledDebounce(this.progress.value);
				}
				// 如果下载完成，隐藏加载中
				if (e && e.state === 4) {
					// uni.hideLoading();
					// uni.showToast({
					// 	title:'下载完成'
					// })
				}

			},
			false
		);

	};
	debounce(progress) {
		uni.showToast({
			icon: 'none',
			title: `已下载${progress}`
		})
	}
	updateProgress = () => {
		uni.showToast({
			title: `已完成${this.progress.value}%`,
		});
	};
}

export default Upgrade;